#include "StarlabDrawArea.h"
#include "Document.h"
#include <QGLWidget>
#include "StarlabException.h"
#include "RenderObject.h"

void StarlabDrawArea::initRendering(){
    // qDebug() << "StarlabDrawArea::initRendering()";

    /// Don't update on a busy document
    if(document->isBusy()) return;
    
    /// For each model in the document
    foreach(Model* model, document->models){
        /// If it was never setup, do it
        if(!model->renderer()->isSetup())
            model->renderer()->setup(model, widget());
        
        /// Update the metadata needed by the renderer
        /// i.e. compute face/vertex normals
        model->renderer()->init();
        
        /// And finally request an OpenGL update
        widget()->update();
    }   
}

StarlabDrawArea::StarlabDrawArea(Document *_document, StarlabSettings *_settings) 
    : document(_document),settings(_settings){}

StarlabDrawArea::~StarlabDrawArea(){
    // qDebug() << "StarlabDrawArea::~StarlabDrawArea()";
    deleteAllRenderObjects();
    if(widget()!=NULL)
        delete widget();
}

void StarlabDrawArea::deleteAllRenderObjects(){
    document->pushBusy();
    foreach(RenderObject::Base* obj, renderObjectList)
        delete obj;
    renderObjectList.clear();
    document->popBusy();
}

void StarlabDrawArea::drawAllRenderObjects(){
    foreach(RenderObject::Base* obj, renderObjectList)
        obj->draw();
}

RenderObject::Triangle& StarlabDrawArea::drawTriangle(QVector3D p1, QVector3D p2, QVector3D p3, QColor color){
    RenderObject::Triangle* triangle = new RenderObject::Triangle(p1,p2,p3,color);
    renderObjectList.append(triangle);
    return *triangle;
}

RenderObject::Point& StarlabDrawArea::drawPoint(QVector3D p1, float size, QColor color){
    RenderObject::Point* point = new RenderObject::Point(p1,size,color);
    renderObjectList.append(point);
    return *point;
}

RenderObject::Segment& StarlabDrawArea::drawSegment(QVector3D p1, QVector3D p2, float size, QColor color){
    RenderObject::Segment* edge = new RenderObject::Segment(p1,p2,size,color);
    renderObjectList.append(edge);
    return *edge;
}

RenderObject::Ray& StarlabDrawArea::drawRay(QVector3D orig, QVector3D dir, float size, QColor color, float scale){
    RenderObject::Ray* edge = new RenderObject::Ray(orig,dir,size,color,scale);
    renderObjectList.append(edge);
    return *edge;
}

void StarlabDrawArea::deleteRenderObject(RenderObject* /*object*/){
    /// @todo 
    throw StarlabException("invalid");
}
